package com.sayice.icemusic.util;

import java.util.Arrays;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 歌词工具类
 *
 * @author shubing
 */
public class LyricUtils {
    private static final Pattern LYRIC_TIME_PATTERN = Pattern.compile("\\[\\d*:\\d*(\\.\\d*)*]");
    private static final Pattern LYRIC_MIN_PATTERN = Pattern.compile("\\[(\\d*)");
    private static final Pattern LYRIC_SEC_PATTERN = Pattern.compile(":(\\d*.\\d*)");
    
    /**
     * 解析歌词，获取每一句的时间和内容
     *
     * @param lyricStr 歌词字符串
     * @return 返回数组：[[第一句的时间，第一句的内容], [第二句的时间，第二句的内容]……]
     */
    public static String[][] parse(String lyricStr) {
        if (lyricStr == null) {
            return new String[0][];
        }
        String[] lines = lyricStr.split("\n");
        if ("".equals(lines[0])) {
            return new String[0][];
        }
        return Arrays.stream(lines).map(line -> {
            Matcher timeMatcher = LYRIC_TIME_PATTERN.matcher(line);
            if (!timeMatcher.find()) {
                return null;
            }
            String timeStr = timeMatcher.group(0);
            String content = line.replaceFirst(LYRIC_TIME_PATTERN.pattern(), "");
            Matcher minMatcher = LYRIC_MIN_PATTERN.matcher(timeStr);
            Matcher secMatcher = LYRIC_SEC_PATTERN.matcher(timeStr);
            if (!minMatcher.find() || !secMatcher.find()) {
                return null;
            }
            int min = Integer.parseInt(minMatcher.group(1));
            float sec = Float.parseFloat(secMatcher.group(1));
            float time = 60 * min + sec;
            return new String[]{String.valueOf(time), content};
        }).filter(Objects::nonNull).toArray(String[][]::new);
    }
}
